package com.fengzhilian.timewheel.runner;

import com.fengzhilian.timewheel.task.TimedTask;
import com.fengzhilian.timewheel.container.Bucket;
import com.fengzhilian.timewheel.container.DelayQueue;
import com.fengzhilian.timewheel.wheel.TimeWheel;
import com.fengzhilian.timewheel.util.DateUtil;

import java.util.Date;
import java.util.List;
/**
 * 时间轮执行器
 * @author 郭智峰
 * @Date 2019年12月25日
 */
public class TaskRunner implements Runnable {
    private TimeWheel timeWheel;
    private DelayQueue delayQueue;
    private String key;
    public TaskRunner(String key,TimeWheel timeWheel,DelayQueue delayQueue) {
        this.timeWheel=timeWheel;
        this.delayQueue=delayQueue;
        this.key=key;
    }
    public void run() {
        while (true){
            timeWheel.setCurrentTimestamp(System.currentTimeMillis());
            int count=0;
            for (Bucket bucket:delayQueue.bucketList ) {
                List<TimedTask> timedTaskList = bucket.list;
                count+=timedTaskList.size();
                for(int i=timedTaskList.size()-1;i>=0;i--)
                {
                    TimedTask timedTask =timedTaskList.get(i);
                    try {
                        if (!timeWheel.addTask(timedTask)) {
                            timedTask.excute(key);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    timedTaskList.remove(timedTask);

                }
            }
            if(count==0){
                System.out.println("没有任务啦,休息一下(延时调度器"+key+")"+ DateUtil.parseDateToStr(new Date(System.currentTimeMillis()), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS, "--null--"));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }
}
